package com.ckfinder.connector.handlers.command;
import java.io.File;
import javax.servlet.http.HttpServletRequest;
import org.w3c.dom.Element;
import com.ckfinder.connector.configuration.Constants;
import com.ckfinder.connector.configuration.IConfiguration;
import com.ckfinder.connector.errors.ConnectorException;
import com.ckfinder.connector.utils.AccessControlUtil;
import com.ckfinder.connector.utils.FileUtils;
public class RenameFileCommand extends XMLCommand implements IPostCommand {
    private String fileName;
    private String newFileName;
    private boolean renamed;
    private boolean addRenameNode;
    @Override
    protected void createXMLChildNodes(final int errorNum,
                                       final Element rootElement) throws ConnectorException {
        if (this.addRenameNode) {
            createRenamedFileNode(rootElement);
        }
    }
    private void createRenamedFileNode(final Element rootElement) {
        Element element = creator.getDocument().createElement("RenamedFile");
        element.setAttribute("name", this.fileName);
        if (renamed) {
            element.setAttribute("newName", this.newFileName);
        }
        rootElement.appendChild(element);
    }
    @Override
    protected int getDataForXml() {
        if (!AccessControlUtil.getInstance(configuration).checkFolderACL(
                this.type, this.currentFolder, this.userRole,
                AccessControlUtil.CKFINDER_CONNECTOR_ACL_FILE_RENAME)) {
            return Constants.Errors.CKFINDER_CONNECTOR_ERROR_UNAUTHORIZED;
        }
        if (configuration.forceASCII()) {
            this.newFileName = FileUtils.convertToASCII(this.newFileName);
        }
        if (this.fileName != null && !this.fileName.equals("")
                && this.newFileName != null && !this.newFileName.equals("")) {
            this.addRenameNode = true;
        }
        int checkFileExt = FileUtils.checkFileExtension(this.newFileName,
                this.configuration.getTypes().get(this.type));
        if (checkFileExt == 1) {
            return Constants.Errors.CKFINDER_CONNECTOR_ERROR_INVALID_EXTENSION;
        }
        if (configuration.ckeckDoubleFileExtensions()) {
            this.newFileName =FileUtils.renameFileWithBadExt(this.configuration.getTypes().get(this.type), this.newFileName);
        }
        if (!FileUtils.checkFileName(this.fileName)
                || FileUtils.checkIfFileIsHidden(this.fileName,
                configuration)) {
            return Constants.Errors.CKFINDER_CONNECTOR_ERROR_INVALID_REQUEST;
        }
        if (!FileUtils.checkFileName(this.newFileName, configuration)
                || FileUtils.checkIfFileIsHidden(this.newFileName,
                configuration)) {
            return Constants.Errors.CKFINDER_CONNECTOR_ERROR_INVALID_NAME;
        }
        if (FileUtils.checkFileExtension(this.fileName,
                this.configuration.getTypes().get(this.type)) == 1) {
            return Constants.Errors.CKFINDER_CONNECTOR_ERROR_INVALID_REQUEST;
        }
        String dirPath = configuration.getTypes().get(this.type).getPath()
                + this.currentFolder;
        File file = new File(dirPath, this.fileName);
        File newFile = new File(dirPath, this.newFileName);
        File dir = new File(dirPath);
        try {
            if (!file.exists()) {
                return Constants.Errors.CKFINDER_CONNECTOR_ERROR_FILE_NOT_FOUND;
            }
            if (newFile.exists()) {
                return Constants.Errors.CKFINDER_CONNECTOR_ERROR_ALREADY_EXIST;
            }
            if (!dir.canWrite() || !file.canWrite()) {
                return Constants.Errors.CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED;
            }
            this.renamed = file.renameTo(newFile);
            if (this.renamed) {
                renameThumb();
                return Constants.Errors.CKFINDER_CONNECTOR_ERROR_NONE;
            } else {
                return Constants.Errors.CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED;
            }
        } catch (SecurityException e) {
            if (configuration.isDebugMode()) {
                throw e;
            } else {
                return Constants.Errors.CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED;
            }
        }
    }
    private void renameThumb() {
        File thumbFile = new File(configuration.getThumbsPath()
                + File.separator + type + this.currentFolder,
                this.fileName);
        File newThumbFile = new File(configuration.getThumbsPath()
                + File.separator + type + this.currentFolder,
                this.newFileName);
        thumbFile.renameTo(newThumbFile);
    }
    @Override
    public void initParams(final HttpServletRequest request,
                           final IConfiguration configuration, final Object... params)
            throws ConnectorException {
        super.initParams(request, configuration);
        this.fileName = getParameter(request, "fileName");
        this.newFileName = getParameter(request, "newFileName");
    }
}
package com.ckfinder.connector.handlers.command;
        import java.io.File;
        import java.io.IOException;
        import java.io.OutputStream;
        import java.text.SimpleDateFormat;
        import java.util.Date;
        import javax.servlet.ServletContext;
        import javax.servlet.http.HttpServletRequest;
        import javax.servlet.http.HttpServletResponse;
        import com.ckfinder.connector.configuration.Constants;
        import com.ckfinder.connector.configuration.IConfiguration;
        import com.ckfinder.connector.errors.ConnectorException;
        import com.ckfinder.connector.utils.AccessControlUtil;
        import com.ckfinder.connector.utils.FileUtils;
        import com.ckfinder.connector.utils.ImageUtils;
public class ThumbnailCommand extends Command {
    private File thumbFile;
    private String ifNoneMatch;
    private long ifModifiedSince;
    private HttpServletResponse response;
    private String fullCurrentPath;
    @Override
    public void setResponseHeader(final HttpServletResponse response,
                                  final ServletContext sc) {
        response.setHeader("Cache-Control", "public");
        String mimetype = getMimeTypeOfImage(sc, response);
        if (mimetype != null) {
            response.setContentType(mimetype);
        }
        response.addHeader("Content-Disposition","attachment;filename=\""+this.fileName+"\"");
        // to fill some params later.
        this.response = response;
    }
    private String getMimeTypeOfImage(final ServletContext sc,
                                      final HttpServletResponse response) {
        if (this.fileName == null || this.fileName.equals("")) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return null;
        }
        String tempFileName = this.fileName.substring(0,
                this.fileName.lastIndexOf('.') + 1).concat(
                FileUtils.getFileExtension(this.fileName).toLowerCase());
        String mimeType = sc.getMimeType(tempFileName);
        if (mimeType == null) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return null;
        }
        return mimeType;
    }
    @Override
    public void execute(final OutputStream out) throws ConnectorException {
        validate();
        createThumb();
        if (setResponseHeadersAfterCreatingFile()) {
            try {
                FileUtils.printFileContentToResponse(thumbFile, out);
            } catch (IOException e) {
                if (configuration.isDebugMode()) {
                    throw new ConnectorException(e);
                }
                try {
                    this.response.sendError(HttpServletResponse.SC_FORBIDDEN);
                } catch (IOException e1) {
                    throw new ConnectorException(e1);
                }
            }
        } else {
            try {
                this.response.reset();
                this.response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
            } catch (IOException e1) {
                throw new ConnectorException(e1);
            }
        }
    }
    @Override
    public void initParams(final HttpServletRequest request,
                           final IConfiguration configuration, final Object... params)
            throws ConnectorException {
        super.initParams(request, configuration, params);
        this.fileName = getParameter(request, "FileName");
        try {
            this.ifModifiedSince = Long.valueOf(request.getDateHeader("If-Modified-Since"));
        } catch (IllegalArgumentException e) {
            this.ifModifiedSince = 0;
        }
        this.ifNoneMatch = request.getHeader("If-None-Match");
    }
    private void validate() throws ConnectorException {
        if (!this.configuration.getThumbsEnabled()) {
            throw new ConnectorException(
                    Constants.Errors.CKFINDER_CONNECTOR_ERROR_THUMBNAILS_DISABLED);
        }
        if (!AccessControlUtil.getInstance(this.configuration).checkFolderACL(
                this.type, this.currentFolder, this.userRole,
                AccessControlUtil.CKFINDER_CONNECTOR_ACL_FILE_VIEW)) {
            throw new ConnectorException(
                    Constants.Errors.CKFINDER_CONNECTOR_ERROR_UNAUTHORIZED);
        }
        if (!FileUtils.checkFileName(this.fileName)) {
            throw new ConnectorException(
                    Constants.Errors.CKFINDER_CONNECTOR_ERROR_INVALID_REQUEST);
        }
        if (FileUtils.checkIfFileIsHidden(this.fileName, this.configuration)) {
            throw new ConnectorException(
                    Constants.Errors.CKFINDER_CONNECTOR_ERROR_FILE_NOT_FOUND);
        }
        File typeThumbDir = new File(configuration.getThumbsPath()
                + File.separator + type);
        try {
            this.fullCurrentPath = typeThumbDir.getAbsolutePath()
                    + currentFolder;
            if (!typeThumbDir.exists()) {
                FileUtils.mkdir(typeThumbDir, configuration);
            }
        } catch (SecurityException e) {
            throw new ConnectorException(
                    Constants.Errors.CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED, e);
        }
    }
    private void createThumb() throws ConnectorException {
        this.thumbFile = new File(fullCurrentPath, this.fileName);
        try {
            if (!thumbFile.exists()) {
                FileorginFile=newFile(configuration.getTypes().get(this.type).getPath()
                        + this.currentFolder, this.fileName);
                if (!orginFile.exists()) {
                    throw new ConnectorException(
                            Constants.Errors.CKFINDER_CONNECTOR_ERROR_FILE_NOT_FOUND);
                }
                try {
                    ImageUtils.createThumb(orginFile, thumbFile, configuration);
                } catch (Exception e) {
                    thumbFile.delete();
                    throw new ConnectorException(
                            Constants.Errors.CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED,e);
                }
            }
        } catch (SecurityException e) {
            throw new ConnectorException(
                    Constants.Errors.CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED, e);
        }
    }
    private boolean setResponseHeadersAfterCreatingFile() throws ConnectorException {
        // Set content size
        File file = new File(this.fullCurrentPath, this.fileName);
        try {		Stringetag=Long.toHexString(file.lastModified()).concat("-").concat(Long.toHexString(file.length()));
            if (etag.equals(this.ifNoneMatch)) {
                return false;
            } else {
                response.setHeader("Etag", etag);
            }
            if (file.lastModified() <= this.ifModifiedSince) {
                return false;
            } else {
                Date date = new Date(System.currentTimeMillis());
                SimpleDateFormat df = new SimpleDateFormat(
                        "EEE, dd MMMM yyyy HH:mm:ss z");
                response.setHeader("Last-Modified", df.format(date));
            }
            response.setContentLength((int) file.length());
        } catch (SecurityException e) {
            throw new ConnectorException(
                    Constants.Errors.CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED, e);
        }
        return true;
    }
}
package com.ckfinder.connector.handlers.command;
        import java.io.File;
        import java.io.IOException;
        import java.io.OutputStream;
        import java.util.regex.Pattern;
        import javax.servlet.ServletContext;
        import javax.servlet.http.HttpServletRequest;
        import javax.servlet.http.HttpServletResponse;
        import com.ckfinder.connector.configuration.Constants;
        import com.ckfinder.connector.configuration.IConfiguration;
        import com.ckfinder.connector.errors.ConnectorException;
        import com.ckfinder.connector.utils.FileUtils;
        import com.ckfinder.connector.utils.PathUtils;
public class ErrorCommand extends Command {
    private ConnectorException e;
    private HttpServletResponse response;
    @Override
    public void execute(final OutputStream out) throws ConnectorException {
        try {
            response.setHeader("X-CKFinder-Error", String.valueOf(e.getErrorCode()));
            switch (e.getErrorCode()) {
                case Constants.Errors.CKFINDER_CONNECTOR_ERROR_INVALID_REQUEST:
                case Constants.Errors.CKFINDER_CONNECTOR_ERROR_INVALID_NAME:
                case Constants.Errors.CKFINDER_CONNECTOR_ERROR_THUMBNAILS_DISABLED:
                case Constants.Errors.CKFINDER_CONNECTOR_ERROR_UNAUTHORIZED:
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
                    break;
                case Constants.Errors.CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED:
                    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    break;
                default:
                    response.sendError(HttpServletResponse.SC_NOT_FOUND);
                    break;
            }
        } catch (IOException e) {
            throw new ConnectorException(e);
        }
    }
    @Override
    public void setResponseHeader(final HttpServletResponse response,
                                  final ServletContext sc) {
        response.reset();
        this.response = response;
    }
    @Override
    public void initParams(final HttpServletRequest request,
                           final IConfiguration configuration, final Object... params)
            throws ConnectorException {
        super.initParams(request, configuration, params);
        e = (ConnectorException) params[0];
    }
    @Override
    protected boolean checkParam(final String reqParam) throws ConnectorException {
        if (reqParam == null || reqParam.equals("")) {
            return true;
        }
        if (Pattern.compile(Constants.INVALID_PATH_REGEX).matcher(reqParam).find()) {
            return false;
        }
        return true;
    }
    @Override
    protected boolean checkHidden()
            throws ConnectorException {
        if (FileUtils.checkIfDirIsHidden(this.currentFolder, configuration)) {
            this.e = new ConnectorException(
                    Constants.Errors.CKFINDER_CONNECTOR_ERROR_CONNECTOR_DISABLED);
            return true;
        }
        return false;
    }
    @Override
    protected boolean checkConnector(final HttpServletRequest request)
            throws ConnectorException {
        if (!configuration.enabled() || !configuration.checkAuthentication(request)) {
            this.e = new ConnectorException(
                    Constants.Errors.CKFINDER_CONNECTOR_ERROR_CONNECTOR_DISABLED);
            return false;
        }
        return true;
    }
    @Override
    protected boolean checkIfCurrFolderExists(final HttpServletRequest request)
            throws ConnectorException {
        String tmpType = getParameter(request, "type");
        File currDir = new File(configuration.getTypes().get(tmpType).getPath()
                + this.currentFolder);
        if (currDir.exists() && currDir.isDirectory()) {
            return true;
        } else {
            this.e = new ConnectorException(
                    Constants.Errors.CKFINDER_CONNECTOR_ERROR_FOLDER_NOT_FOUND);
            return false;
        }
    }
    @Override
    protected void getCurrentFolderParam(final HttpServletRequest request) {
        String currFolder = getParameter(request, "currentFolder");
        if (!(currFolder == null || currFolder.equals(""))) {
            this.currentFolder = PathUtils.addSlashToBeginning(PathUtils.addSlashToEnd(currFolder));
        }
    }
}
package com.ckfinder.connector.handlers.command;
        import java.io.IOException;
        import java.io.OutputStream;
        import javax.servlet.ServletContext;
        import javax.servlet.http.HttpServletRequest;
        import javax.servlet.http.HttpServletResponse;
        import org.w3c.dom.Element;
        import com.ckfinder.connector.configuration.Constants;
        import com.ckfinder.connector.configuration.IConfiguration;
        import com.ckfinder.connector.errors.ConnectorException;
        import com.ckfinder.connector.utils.AccessControlUtil;
        import com.ckfinder.connector.utils.XMLCreator;
public abstract class XMLCommand extends Command {
    public void setResponseHeader(final HttpServletResponse response,
                                  final ServletContext sc) {
        response.setContentType("text/xml");
        response.setHeader("Cache-Control", "no-cache");
        response.setCharacterEncoding("utf-8");
    }
    public void execute(final OutputStream out) throws ConnectorException {
        try {
            createXMLResponse(getDataForXml());
            out.write(creator.getDocumentAsText().getBytes("UTF-8"));
        } catch (ConnectorException e) {
            throw e;
        } catch (IOException e) {
            thrownewConnectorException(Constants.Errors.CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED, e);
        }
    }
    private void createXMLResponse(final int errorNum) throws ConnectorException {
        if (configuration.isDebugMode() && this.exception != null) {
            throw new ConnectorException(this.exception);
        }
        Element rootElement = creator.getDocument().createElement("Connector");
        if (this.type != null && !type.equals("")) {
            rootElement.setAttribute("resourceType", this.type);
        }
        if (mustAddCurrentFolderNode()) {
            createCurrentFolderNode(rootElement);
        }
        creator.addErrorCommandToRoot(rootElement, errorNum, getErrorMsg(errorNum));
        createXMLChildNodes(errorNum, rootElement);
        creator.getDocument().appendChild(rootElement);
    }
    protected String getErrorMsg(final int errorNum) {
        return null;
    }
    protected abstract void createXMLChildNodes(final int errorNum,
                                                final Element rootElement)
            throws ConnectorException;
    protected abstract int getDataForXml();
    protected void createCurrentFolderNode(final Element rootElement) {
        Element element = creator.getDocument().createElement("CurrentFolder");
        element.setAttribute("path", this.currentFolder);
        element.setAttribute("url", configuration.getTypes().get(this.type).getUrl()
                + this.currentFolder);
        element.setAttribute("acl", String.valueOf(AccessControlUtil.getInstance(configuration).checkACLForRole(this.type,
                this.currentFolder, this.userRole)));
        rootElement.appendChild(element);
    }
    @Override
    public void initParams(final HttpServletRequest request,
                           final IConfiguration configuration, final Object... params)
            throws ConnectorException {
        super.initParams(request, configuration, params);
        creator = new XMLCreator();
        creator.createDocument();
    }
    protected boolean mustAddCurrentFolderNode() {
        return true;
    }
}